package com.rmuti.datastructure.list;

public class SelfAdjustingList {
	private class LinkedNode {
		private Object element;
		private LinkedNode next;

		LinkedNode(Object e) {
			element = e;
		}

		LinkedNode(Object e, LinkedNode p) {
			element = e;
			next = p;
		}

	}

	private LinkedNode header;
	private int size;

	public SelfAdjustingList() {
		header = new LinkedNode(null);
		size = 0;
	}

	public void add(int i, Object e) {
		LinkedNode p = nodeAt(i - 1);
		p.next = new LinkedNode(e, p.next);
		size++;
	}

	public void add(Object e) {
		add(size, e);
	}

	public Object get(int i) {
		return nodeAt(i).element;
	}

	public boolean contain(Object e) {
		LinkedNode node = nodeOf(e);
		if (node == null)
			return false;

		LinkedNode previosNode = findPrevious(node);
		LinkedNode tmpNode = header.next;
		previosNode.next = node.next;
		header.next = node;
		node.next = tmpNode;
		return true;
	}

	public LinkedNode findPrevious(Object e) {
		LinkedNode node = header;
		while (node.next != null && !node.next.element.equals(e)) {
			node = node.next;
		}
		return node;
	}

	private LinkedNode nodeAt(int n) {
		LinkedNode p = header;
		for (int i = -1; i < n; i++) {
			p = p.next;
		}
		return p;
	}

	private LinkedNode nodeOf(Object e) {
		LinkedNode node = header.next;
		while (node != null && !node.element.equals(e)) {
			node = node.next;
		}
		return node;
	}

	@Override
	public String toString() {
		String str = "";
		LinkedNode node = header.next;
		while (node != null) {
			str += node.element;
			node = node.next;
		}
		return str;
	}

	public static void main(String[] args) {
		SelfAdjustingList selfList = new SelfAdjustingList();
		selfList.add("a");
		selfList.add("e");
		selfList.add("i");
		selfList.add("o");
		selfList.add("u");

//		System.out.println(selfList.findPrevious("i").element);
//		System.out.println(selfList);

		// System.out.println(selfList);
		//
//		 selfList.contain("e");
//		 System.out.println(selfList);

		 selfList.contain("i");
		 System.out.println(selfList);

	}

}
